package com.leizi.igym.job.once;

import cn.hutool.core.collection.CollectionUtil;
import com.leizi.igym.dao.PlanESDao;
import com.leizi.igym.dao.PostESDao;
import com.leizi.igym.domain.Plan;
import com.leizi.igym.domain.Post;
import com.leizi.igym.domain.User;
import com.leizi.igym.dto.PostESDTO;
import com.leizi.igym.service.PlanService;
import com.leizi.igym.service.PostService;
import com.leizi.igym.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: leizi0110
 * @CreateTime: 2024-04-23  19:46
 * @Description:
 */

@Slf4j
@Component
public class SelectPostToES implements CommandLineRunner {

    @Resource
    private PostService postService;

    @Resource
    private UserService userService;

    @Resource
    private PostESDao postESDao;

    @Override
    public void run(String... args) throws Exception {
        List<Post> postList = postService.list();
        if (CollectionUtil.isEmpty(postList)) {
            return;
        }
        List<PostESDTO> postESDTOList = postList.stream().map(post -> {
            User user = userService.getById(post.getUserId());
            PostESDTO postESDTO = new PostESDTO();
            BeanUtils.copyProperties(post, postESDTO);
            postESDTO.setAvatar(user.getAvatar());
            postESDTO.setNickname(user.getNickname());
            return postESDTO;
        }).toList();
        final int pageSize = 500;
        int total = postList.size();
        log.info("SelectPlanToES start, total {}", total);
        for (int i = 0; i < total; i += pageSize) {
            int end = Math.min(i + pageSize, total);
            log.info("sync from {} to {}", i, end);
            postESDao.saveAll(postESDTOList.subList(i, end));
        }
        log.info("SelectPlanToES end, total {}", total);
    }
}
